package com.haixiaoke.saas.material.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.material.domain.MaterialGroup;
import com.haixiaoke.saas.material.mapper.MaterialGroupMapper;
import com.haixiaoke.saas.material.service.IMaterialGroupService;
import com.haixiaoke.saas.material.service.IMaterialPhotoService;
import com.haixiaoke.saas.common.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.haixiaoke.saas.system.framework.security.util.SecurityUtils.getUsername;

/**
 * 素材组Service业务层处理
 * 
 * @author panda
 * @date 2023-12-25
 */
@Service
public class MaterialGroupServiceImpl implements IMaterialGroupService {
    @Autowired
    private MaterialGroupMapper materialGroupMapper;
    @Autowired
    private IMaterialPhotoService iMaterialPhotoService;

    /**
     * 查询素材组
     * 
     * @param groupId 素材组主键
     * @return 素材组
     */
    @Override
    public MaterialGroup selectMaterialGroupByGroupId(Long groupId) {
        return materialGroupMapper.selectMaterialGroupByGroupId(groupId);
    }

    /**
     * 查询素材组列表
     * 
     * @param materialGroup 素材组
     * @return 素材组
     */
    @Override
    public List<MaterialGroup> selectMaterialGroupList(MaterialGroup materialGroup) {
        return materialGroupMapper.selectMaterialGroupList(materialGroup);
    }

    /**
     * 新增素材组
     * 
     * @param materialGroup 素材组
     * @return 结果
     */
    @Override
    public int insertMaterialGroup(MaterialGroup materialGroup) {
        materialGroup.setCreateTime(DateUtils.getNowDate());
        MaterialGroup group = materialGroupMapper.selectMaterialGroupByGroupId(materialGroup.getParentId());
        if (ObjectUtil.isNotEmpty(group)) {
            materialGroup.setAncestors(group.getAncestors() + "," + materialGroup.getParentId());
        } else {
            materialGroup.setAncestors(String.valueOf(materialGroup.getParentId()));
        }
        return materialGroupMapper.insertMaterialGroup(materialGroup);
    }

    /**
     * 修改素材组
     * 
     * @param materialGroup 素材组
     * @return 结果
     */
    @Override
    public int updateMaterialGroup(MaterialGroup materialGroup) {
        if (materialGroup.getGroupId().equals(materialGroup.getParentId())) {
            throw new ServiceException("数据异常，不能设置自己为父级结构");
        }
        materialGroup.setUpdateTime(DateUtils.getNowDate());
        MaterialGroup parentGroup = materialGroupMapper.selectMaterialGroupByGroupId(materialGroup.getParentId());
        MaterialGroup group = materialGroupMapper.selectMaterialGroupByGroupId(materialGroup.getGroupId());
        if (ObjectUtil.isNotEmpty(parentGroup) && ObjectUtil.isNotEmpty(group)) {
            String newAncestors = parentGroup.getAncestors() + "," + parentGroup.getGroupId();
            String oldAncestors = group.getAncestors();
            materialGroup.setAncestors(newAncestors);
            updateGroupChildren(materialGroup.getGroupId(),newAncestors,oldAncestors);
        } else if (ObjectUtil.isEmpty(parentGroup) && ObjectUtil.isNotEmpty(group)){
            String newAncestors = "0";
            String oldAncestors = group.getAncestors();
            materialGroup.setAncestors(newAncestors);
            updateGroupChildren(materialGroup.getGroupId(),newAncestors,oldAncestors);
        }
        return materialGroupMapper.updateMaterialGroup(materialGroup);
    }

    private void updateGroupChildren(Long groupId, String newAncestors, String oldAncestors) {
        Date nowDate = DateUtils.getNowDate();
        List<MaterialGroup> materialGroupList = materialGroupMapper.selectGroupChildrenByGroupId(groupId);
        for (MaterialGroup group : materialGroupList) {
            group.setAncestors(group.getAncestors().replaceFirst(oldAncestors, newAncestors));
            group.setUpdateTime(nowDate);
            group.setUpdateBy(getUsername());
        }
        if (!materialGroupList.isEmpty()) {
            materialGroupMapper.updateBatchGroup(materialGroupList);
        }
    }

    /**
     * 批量删除素材组
     * 
     * @param groupIds 需要删除的素材组主键
     * @return 结果
     */
    @Override
    public int deleteMaterialGroupByGroupIds(Long[] groupIds) {
        return materialGroupMapper.deleteMaterialGroupByGroupIds(groupIds);
    }

    /**
     * 删除素材组信息
     * 
     * @param groupId 素材组主键
     * @return 结果
     */
    @Override
    public int deleteMaterialGroupByGroupId(Long groupId) {
        return materialGroupMapper.deleteMaterialGroupByGroupId(groupId);
    }

    /**
     * 查询该租户下的素材组树状结构
     * @param materialGroup 查询条件
     * @return  树状结构
     */
    @Override
    public List<Node> selectGroupTreeList(MaterialGroup materialGroup) {
        List<MaterialGroup> materialGroups = materialGroupMapper.selectGroupTreeList(materialGroup);
        List<MaterialGroup> treeList = selectBuildTreeList(materialGroups);
        return treeList.stream().map(Node::new).collect(Collectors.toList());
    }

    /**
     * 软删除素材组
     * @param group
     * @return
     */
    @Override
    public int softDeleteMaterialGroupByGroupIds(MaterialGroup group) {
        iMaterialPhotoService.softDeletePhotoByGroupIds(group);
        return materialGroupMapper.softDeleteMaterialGroupByGroupIds(group);
    }

    private List<MaterialGroup> selectBuildTreeList(List<MaterialGroup> materialGroups) {
        List<MaterialGroup> list = new ArrayList<>();
        List<Long> groupIds = materialGroups.stream().map(MaterialGroup::getGroupId).collect(Collectors.toList());
        for (MaterialGroup materialGroup : materialGroups) {
            //如果是根节点，则获取子节点所有数据
            if (!groupIds.contains(materialGroup.getParentId())) {
                buildTreeList(materialGroups,materialGroup);
                list.add(materialGroup);
            }
        }
        if (list.isEmpty()) {
            list = materialGroups;
        }
        return list;
    }

    private void buildTreeList(List<MaterialGroup> materialGroups, MaterialGroup materialGroup) {
        //获取子节点所有数据
        List<MaterialGroup> childList = getChildList(materialGroups,materialGroup);
        materialGroup.setChildren(childList);
        for (MaterialGroup group : childList) {
            if (hashChild(materialGroups,group)) {
                buildTreeList(materialGroups,group);
            }
        }
    }

    private boolean hashChild(List<MaterialGroup> materialGroups, MaterialGroup materialGroup) {
        return !getChildList(materialGroups, materialGroup).isEmpty();
    }

    private List<MaterialGroup> getChildList(List<MaterialGroup> materialGroups, MaterialGroup materialGroup) {
        List<MaterialGroup> list = new ArrayList<>();
        Iterator<MaterialGroup> iterator = materialGroups.iterator();
        while (iterator.hasNext()){
            MaterialGroup group = (MaterialGroup) iterator.next();
            if (group.getParentId() != null && group.getParentId().equals(materialGroup.getGroupId())) {
                list.add(group);
            }
        }
        return list;
    }

}
